import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    ScrollView,
    TextInput,
    Linking,
    DeviceEventEmitter
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import Loading from "../../utils/Loading";
import { StackActions } from '@react-navigation/native';
import Header from "../../components/header";

let navigation

export default class DutyOperation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAdd: this.props.route && this.props.route.params && this.props.route.params.isAdd ? this.props.route.params.isAdd : false,
            roleId: this.props.route && this.props.route.params && this.props.route.params.roleId ? this.props.route.params.roleId : '',
            totalDuties: this.props.route && this.props.route.params && this.props.route.params.totalDuties ? JSON.parse(this.props.route.params.totalDuties) : [],
            roleName: '',
            roleDesc: '',
            dataArray: [],
        }
    }

    componentDidMount() {
        if (this.state.isAdd) {
            this.fetchPermissions()
        } else {
            this.getDutyDetail()
        }
        
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={this.state.isAdd ? '添加职务' : '编辑职务'} RightButton={() => this.renderRightButton()}></Header>

                <ScrollView style={{ flex: 1 }}>
                    {this.renderHeader()}
                    {
                        this.state.dataArray && this.state.dataArray.map((item, index) => {
                            return (
                                this.renderItemView(item, index)
                            )
                        })
                    }
                    {
                        !this.state.isAdd && this.state.dataArray.length > 0 ?
                            <View style={[styles.deleteBg, { marginBottom: Constant.bottomHeight + 15 }]}>
                                <TouchableOpacity
                                    style={styles.deleteBox}
                                    onPress={()=>{
                                        this.deleteDuty()
                                    }}
                                >
                                    <Text style={styles.deleteText}>删除职务</Text>
                                </TouchableOpacity>
                            </View>
                            :
                            null
                    }
                </ScrollView>

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }

    renderHeader() {
        return (
            <View style={styles.headerBox}>
                <View style={styles.dutyNameBox}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', width: 75 }}>
                        <Text style={styles.dutyNameTitle}>职务名称</Text>
                        <Text style={[styles.dutyNameTitle, { color: 'red', marginLeft: 5 }]}>*</Text>
                    </View>
                    <TextInput
                        clearButtonMode='while-editing'
                        style={styles.textInput}
                        placeholder='请输入职务名称'
                        returnKeyType='done'
                        value={this.state.roleName}
                        onChangeText={this.onChangeRoleTextHandle}
                    />
                    <View style={styles.sepLine} />
                </View>
                <View style={styles.dutyNameBox}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', width: 75 }}>
                        <Text style={styles.dutyNameTitle}>职务介绍</Text>
                    </View>
                    <TextInput
                        clearButtonMode='while-editing'
                        style={styles.textInput}
                        placeholder='一句话介绍该职务'
                        returnKeyType='done'
                        value={this.state.roleDesc}
                        onChangeText={this.onChangeRoleDesTextHandle}
                    />
                </View>
                <View style={{ width: '100%', height: 10 }} />
                <View style={styles.dutyNameBox}>
                    <Text style={[styles.dutyNameTitle, { fontSize: 17 }]}>授权权限</Text>
                </View>
            </View>
        )
    }

    renderItemView(item, index) {
        return (
            <TouchableOpacity
                style={styles.dutyBox}
                key={index}
                onPress={() => {
                    let dataArray = []
                    this.state.dataArray.map((permission) => {
                        if (permission.permId == item.permId) {
                            permission.select = !permission.select
                        }
                        dataArray.push(permission)
                    })
                    this.setState({
                        dataArray: dataArray
                    })
                }}
            >
                <Image style={styles.dutyStatusImg} source={item.select ? require('source/image/agent_check.png') : require('source/image/agent_uncheck.png')} />
                <Text style={[styles.dutyName, { color: item.select ? '#f8603a' : '#333' }]}>{item.permName}</Text>
                {
                    index < this.state.dataArray.length-1 ?
                    <View style={styles.sepLine} />
                    :
                    null

                }
                
            </TouchableOpacity>
        )
    }

    renderRightButton() {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={this.save}>
                <View style={styles.rightBox}>
                    <Text style={styles.rightText}>保存</Text>
                </View>
            </TouchableOpacity>
        )
    }

    deleteDuty() {
        Alert.alert('删除职务', '是否确认删除此职务?',
                    [{ text: "取消" },
                    {
                        text: "确定", onPress: () => {
                            let param = {
                                merchantId: Constant.userInfo.merchantId,
                                roleId: this.state.roleId
                            }
                            this.Loading.show('删除中...')
                            HttpUtils.postRequest(HttpUrls.deleteRole, param)
                                .then((result) => {
                                    this.Loading.hide()
                                    if (result.code == 0) {
                                        DeviceEventEmitter.emit('deleteRoleSuccess', {roleId: this.state.roleId});
                                        navigation.dispatch(StackActions.pop(2));
                                    } else {
                                        ToastToUser(result.msg ? result.msg : result.statusText)
                                    }
                                })
                                .catch((error) => {
                                    this.Loading.hide()
                                });
                        }
                    }]
                )
    }

    save = () => {
        if (this.state.roleName.length == 0) {
            ToastToUser('职务名称不能为空!')
            return
        }
        let isExisted = false
        this.state.totalDuties.map((item) => {
            if (item.roleName == this.state.roleName && item.roleId != this.state.roleId) {
                isExisted = true
            }
        })
        if (isExisted) {
            ToastToUser('职务已存在!')
            return
        }

        let permissionIds = []
        this.state.dataArray.map((item) => {
            if (item.select) {
                permissionIds.push(item.permId)
            }
        })

        if (this.state.isAdd) {
            if (this.Loading) {
                this.Loading.show();
            }
            let param = {
                merchantId: Constant.userInfo.merchantId,
                roleName: this.state.roleName,
                roleDesc: this.state.roleDesc,
                initPermId: permissionIds,
            }
            HttpUtils.postRequest(HttpUrls.addRole, param)
                .then((result) => {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                    if (result.code == 0) {
                        if (this.props.route.params && this.props.route.params.completion) {
                            this.props.route.params.completion()
                        }
                    } else {
                        ToastToUser(result.msg ? result.msg : result.statusText)
                    }
                })
                .catch((error) => {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                });
        } else {
            if (this.Loading) {
                this.Loading.show();
            }
            let param = {
                merchantId: Constant.userInfo.merchantId,
                roleName: this.state.roleName,
                roleDesc: this.state.roleDesc,
                initPermId: permissionIds,
                roleId: this.state.roleId
            }
            HttpUtils.postRequest(HttpUrls.updateRole, param)
                .then((result) => {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                    if (result.code == 0) {
                        if (this.props.route.params && this.props.route.params.completion) {
                            this.props.route.params.completion()
                        }
                    } else {
                        ToastToUser(result.msg ? result.msg : result.statusText)
                    }
                })
                .catch((error) => {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                });
        }
    }

    onChangeRoleTextHandle = (value) => {
        this.setState({
            roleName: value
        })
    }

    onChangeRoleDesTextHandle = (value) => {
        this.setState({
            roleDesc: value
        })
    }

    fetchPermissions(dutyPermissions) {
        HttpUtils.getRequest(HttpUrls.getPermissions, {})
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data

                let dataArray = []
                data.map((item) => {
                    dutyPermissions && dutyPermissions.map((item1) => {
                        if (item.permId == item1.permId) {
                            item.select = true
                        }
                    })
                    dataArray.push(item)
                })

                this.setState({
                    dataArray: dataArray
                })
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getDutyDetail() {
        if (this.Loading) {
            this.Loading.show();
        }
        let param = {
            merchantId: Constant.userInfo.merchantId,
            roleId: this.state.roleId
        }
        HttpUtils.postRequest(HttpUrls.getMerchantRoleDetail, param)
            .then((result) => {
                let data = result.data
                this.setState({
                    roleName: data.roleName,
                    roleDesc: data.roleDesc,
                }, function () {
                    this.fetchPermissions(data.permissionList)
                })
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
    },
    headerBox: {
        flexDirection: 'column',
        width: '100%',
    },
    dutyNameBox: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
        backgroundColor: '#fff'
    },
    dutyNameTitle: {
        color: '#333',
        fontSize: 15
    },
    textInput: {
        marginLeft: 10,
        flex: 1,
        height: '100%'
    },
    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 15,
        width: '100%',
        height: 0.3,
        backgroundColor: '#d4d4d4',
    },
    dutyBox: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        paddingLeft: 15,
        backgroundColor: '#fff'
    },
    dot: {
        width: 10,
        height: 10,
        borderRadius: 5,
        backgroundColor: '#333'
    },
    dutyStatusImg: {
        width: 20,
        height: 20
    },
    dutyName: {
        color: '#333',
        fontSize: 17,
        marginLeft: 8,
    },

    deleteBg: {
        width: '100%',
        height: 70,
        paddingHorizontal: 15,
        backgroundColor: '#fff'
    },
    deleteBox: {
        marginTop: 15,
        width: '100%',
        height: 40,
        backgroundColor: '#FF4F2C',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 4
    },
    deleteText: {
        color: '#fff',
        fontSize: 15
    }

})